package com.broada.apm.service.impl;

import java.util.Date;
import java.util.List;

import com.broada.apm.ajax.IndicatorResult;
import com.broada.apm.ajax.PerformanceResult;
import com.broada.apm.ajax.ResourceResult;
import com.broada.apm.base.BaseService;
import com.broada.apm.cache.IndicatorItemManager;
import com.broada.apm.entity.IndicatorItem;
import com.broada.apm.entity.Service;
import com.broada.apm.entity.TradePerformance;
import com.broada.apm.model.Resource;
import com.broada.apm.service.KeyTradeService;

public class KeyTradeServiceImpl extends BaseService implements KeyTradeService {
	
//	private static final Logger logger = LoggerFactory.getLogger(KeyTradeServiceImpl.class);

	@Override
	public ResourceResult queryKeyTradeByPage(String appId) {
		ResourceResult result = new ResourceResult();
		List<Resource> list = resLogic.queryKeyTrade(appId);
		result.addData("result", list);
		return result;
	}

	@Override
	public ResourceResult queryKeyTradeByKey(String tradeId) {
		ResourceResult result = new ResourceResult();
		
		Resource res = resLogic.queryKeyResourceById(tradeId);
		result.setResource(res);
		return result;
	}

	@Override
	public PerformanceResult queryResourcePerformanceSubTotal(String appId, String keyWord, long startDate, long endDate) {
		if (endDate == 0)
			endDate = System.currentTimeMillis();
		if (startDate == 0)
			startDate = endDate - 60 * 60 * 1000;
		PerformanceResult result = new PerformanceResult();
		List<TradePerformance> tradePerfs = tradePerformanceLogic.getKeyTradePerformanceSubTotal(appId, keyWord,
				new Date(startDate), new Date(endDate));
		result.setTradePerformance(tradePerfs);
		return result;
	}

	@Override
	public IndicatorResult queryIndicators(String appId, String tradeId) {
		IndicatorResult result = new IndicatorResult();
		Resource res = resLogic.queryKeyResourceById(tradeId);
		String serviceId = res.getBelongTo();
		if (!res.getBelongTo().contains("-")) {
			serviceId = res.getApplicationId() + "-" + res.getBelongTo();
		}
		Service service = serverLogic.queryServiceById(serviceId);
		if (service == null) {
			return result;
		}
		IndicatorItem[] items = IndicatorItemManager.getInstance().getTransIndicatorItems(res.getId(), (service.getProtocol() == 0 ? service.getAutoDiscoveryProtocol() : service.getProtocol()));
		result.setIndictorItems(items);
		return result;
	}
	
}
